﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Serialization.Attributes.Annotations
{
    [AttributeUsage(AttributeTargets.Property)]
    public class DigitAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
    {
        private static List<Type> ValidTypes = new List<Type>()
        {
            typeof(Int16),
            typeof(Int32),
            typeof(Int64),
            typeof(UInt16),
            typeof(UInt32),
            typeof(UInt64),
            typeof(float),
            typeof(double),
            typeof(decimal)
        };
        public readonly int ExactNumberOfDigits;

        public DigitAttribute(int exactNumberOfDigits)
        {
            if (exactNumberOfDigits < 0)
                throw new ArgumentException("The exact number of digits specified must be greater than or equal to 0.");

            this.ExactNumberOfDigits = exactNumberOfDigits;
        }

        public override bool IsValid(object value)
        {
            if (!ValidTypes.Contains(value.GetType()))
                throw new ArgumentException("The value specified is not a valid type.");

            int valueLength = value.ToString().Replace(".", "").Length;
            return valueLength == ExactNumberOfDigits;
        }
    }
}
